/**
 *******************************************************************************
 * @file      pxx_driver.c
 * @version   V1.0.0    
 * @date      2013.05.04
 * @brief     pxx pulse driver for Tananis on PA7.	
 *            Resources: 
 *                 TIM8_UP
 *                 DMA2_Stream1, channel 7
 *            By writing, the data stream is converted into ppm pulses,
 *            with CCR1=16(8us), ARR=32(16us) presenting for "0"
 *            ARR=48(24us) presenting for "1"
 * @author    - Adela 
 *            - Robert Zhang <armner@gmail.com>
 *            - 
 */

#include "stm32f2xx.h"
#include "pxx_driver.h"
#include "interrupt.h"
#include "FreeRTOS.h"
#include "semphr.h"

void DMA2_Stream1_IRQHandler_pxx();
static xSemaphoreHandle pxx_sema=NULL;
static uint16_t pxx_stream[400];
static char pxx_frame[18]={0xFF,0xFF,0xFF,0xFF,0xFF};

/** @brief  initialize GPIO, DMA, TIM, and other driver data
*/
int pxx_open(Driver *driver)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    int i;

    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);

    GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_TIM8);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOA, &GPIO_InitStructure);


    //create a flag for waiting
    vSemaphoreCreateBinary(pxx_sema);
    if(pxx_sema ==NULL)
    {
        return -1;
    }
    
    DMA2_Stream1_Interrupt_Handler = DMA2_Stream1_IRQHandler_pxx;
    //get system clocks
    RCC_ClocksTypeDef RCC_Clocks;
        
    RCC_GetClocksFreq( &RCC_Clocks);
    
    for(i=0; i<400; i++)
    {
        pxx_stream[i] = 32;
    }
    
    RCC->APB2ENR |= RCC_APB2ENR_TIM8EN ;            // Enable clock
    RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN ;            // Enable DMA2 clock

    DMA_InitTypeDef DMA_InitStructure;

    DMA_DeInit(DMA2_Stream1);
    DMA_InitStructure.DMA_Channel = DMA_Channel_7;  
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&(TIM8->ARR) ;
    DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)pxx_stream;
    DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
    DMA_InitStructure.DMA_BufferSize = 400;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
    DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
    DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
    DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;
    DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
    DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;

    DMA_Init(DMA2_Stream1, &DMA_InitStructure);

    //config TIM1 as 9ms pulse driver
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
    TIM_OCInitTypeDef  TIM_OCInitStructure;    

    /* Time Base configuration */
    TIM_TimeBaseStructure.TIM_Prescaler = (RCC_Clocks.PCLK2_Frequency*2) / 2000000 - 1 ;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseStructure.TIM_Period = 20;
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;

    TIM_TimeBaseInit(TIM8, &TIM_TimeBaseStructure);

    /* Channel 1 Configuration in PWM mode */
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
    TIM_OCInitStructure.TIM_Pulse = 16;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
    TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
    TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
    TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Set;

    TIM_OC1Init(TIM8, &TIM_OCInitStructure);
    
    /* DMA enable*/
    DMA_Cmd(DMA2_Stream1, ENABLE);
    DMA_ITConfig(DMA2_Stream1,DMA_IT_TC,ENABLE);
    
    TIM_DMAConfig(TIM8, TIM_DMABase_ARR, TIM_DMABurstLength_1Transfer);
    TIM_DMACmd(TIM8, TIM_DMA_Update, ENABLE);

    /* Main Output Enable */
    TIM_CtrlPWMOutputs(TIM8, ENABLE);

    /* TIM1 counter enable */
    //TIM_Cmd(TIM8, ENABLE);
  
    NVIC_EnableIRQ(DMA2_Stream1_IRQn) ;
    
    return 0;
}

/** @brief  write a packet to driver buffer, 
 *          the driver buffer is protected by disable interrupt
 */
int pxx_write(Driver *driver, void *buffer, int len, OFFSET offset)
{
    char *p_char;
    int i;
    
    if( (len) > sizeof(pxx_frame)) return -1;
    
    DMA_ITConfig(DMA2_Stream1,DMA_IT_TC,DISABLE);

   
    p_char =buffer;
    for(i=0; i<len; i++)
    {
        pxx_frame[i] = *p_char++;
    }

    DMA_ITConfig(DMA2_Stream1,DMA_IT_TC,ENABLE);

    TIM_Cmd(TIM8, ENABLE);

    return len;
}

/** @brief  User task calling of this function would be pended
 *          user task can be waked up by heart-beat pulse 
*/
int pxx_read(Driver *driver, void *buffer, int len, OFFSET offset)
{
    xSemaphoreTake(pxx_sema, portMAX_DELAY);
    return 0;
}

/** @brief  GPIO returns to its default state
 *          DMA to its default state
 *          TIM8 to its default state
 *          IRQ to its default state
 *          release other resources used
 */
int pxx_close(Driver *driver)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
 
    DMA_DeInit(DMA2_Stream1);
    TIM_DeInit(TIM8);
    
    NVIC_DisableIRQ(DMA2_Stream1_IRQn) ;
    
    vSemaphoreDelete(pxx_sema);
    return 0;
}

/** @brief  Cnnvert frame to pwm streams
 *          release read pending
 */
void DMA2_Stream1_IRQHandler_pxx()
{
     static signed portBASE_TYPE xHigherPriorityTaskWoken;

    if(DMA_GetITStatus(DMA2_Stream1, DMA_IT_TCIF1))
    {
        DMA_ClearITPendingBit(DMA2_Stream1, DMA_IT_TCIF1);  
    
        xHigherPriorityTaskWoken =pdFALSE;
        xSemaphoreGiveFromISR(pxx_sema, &xHigherPriorityTaskWoken);
    }
    else
    {
        return;
    }
    if(0){
        #include "led_driver.h"
        static char t;

        t^=1;
        led_driver.write(&led_driver,&t,sizeof(t),0);
    }
    
    //bits to ppm streams
    uint16_t *p_uint16;
    {
        char t_char;
        char count_1s;
        int i;
        
        p_uint16 =pxx_stream;
        
        //header
        *p_uint16++ =32;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =32;
        
        count_1s =0;
        for(i=0; i<sizeof(pxx_frame); i++)
        {
            int j;
            t_char =pxx_frame[i];
            for(j=0; j<8; j++)
            {
                //MSB first
                if(t_char &0x80)
                {
                    *p_uint16++ =32;
                    count_1s =0;
                }
                else
                {
                    *p_uint16++ =48;
                    count_1s ++;
                    if(count_1s ==5)
                    {
                        //add dummy "0"
                        count_1s =0;
                        *p_uint16++ =32;
                    }
                }
                t_char <<=1;
            }
        }
        
        //tail
        *p_uint16++ =32;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =48;
        *p_uint16++ =32;
    }
    
    int count;
    count = (uint32_t)p_uint16 - (uint32_t)pxx_stream;
    count /=2;
    
    //fire DMA
    DMA_InitTypeDef DMA_InitStructure;

    DMA_DeInit(DMA2_Stream1);
    DMA_InitStructure.DMA_Channel = DMA_Channel_7;  
    DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&(TIM8->ARR) ;
    DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)pxx_stream;
    DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;
    DMA_InitStructure.DMA_BufferSize = count;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_PeripheralDataSize_HalfWord;
    DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;
    DMA_InitStructure.DMA_Priority = DMA_Priority_VeryHigh;
    DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;
    DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;
    DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;
    DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;

    DMA_Init(DMA2_Stream1, &DMA_InitStructure);

    DMA_Cmd(DMA2_Stream1, ENABLE);
    DMA_ITConfig(DMA2_Stream1,DMA_IT_TC,ENABLE);
}


Driver pxx_driver =
{
    &pxx_open,
    &pxx_write,
    &pxx_read,
    NULL,
    &pxx_close
};

